package com.stb.llh.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Lee
 * @Date 2021/11/3
 * @Description
 */

@WebFilter(filterName = "loginFilter",urlPatterns = {"/user/*","/admin/*"})
public class LoginFilter implements Filter {
    //初始化调用的方法
    //当服务器 被启动的时候，调用
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("哎呀，我被生出来了！！！");
    }

    //拦截的方法
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {



        HttpServletRequest req = (HttpServletRequest) servletRequest;

        String url = req.getRequestURL().toString();
        System.out.println(url);



        if("post".equalsIgnoreCase(req.getMethod())){
            filterChain.doFilter(servletRequest,servletResponse);
        }

        if(url.contains("admin")){
            if(req.getSession().getAttribute("admin")!=null){
                filterChain.doFilter(servletRequest,servletResponse);
            }
            else{
                HttpServletResponse httpServletResponse=(HttpServletResponse)servletResponse;
                System.out.println("哈哈 被拦截了吧！！！");
                httpServletResponse.sendRedirect("/notFoundAdmin");

            }
        }
        else if(url.contains("user")){
            if(req.getSession().getAttribute("user")!=null){
                filterChain.doFilter(servletRequest,servletResponse);
            }
            else{
                HttpServletResponse httpServletResponse=(HttpServletResponse)servletResponse;
                System.out.println("哈哈 被拦截了吧！！！");
                httpServletResponse.sendRedirect("/notFoundUser");

            }
        }


    }

    //销毁时候调用的方法
    @Override
    public void destroy() {
        System.out.println("哎呀，我要被销毁了！！！");

    }

}
